<template>
  <view class="sign-in" :style="{ paddingTop: `${totalNavigationHeight * 2}rpx` }">
    <NavigationBar navigation-title="签到" />

    <view class="sign-title">
      <text class="title-text">
        签到打卡
      </text>
      <text class="title-info">
        连续签到每日可额外获得5星币
      </text>
      <image class="sign-img" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/sign_ip.png" />
    </view>

    <view class="sign-content">
      <view class="content-top">
        <view class="top-item">
          <text class="item-label">
            已连续签到
          </text>
          <text class="item-text">
            {{ accountData?.lastDay }}天
          </text>
        </view>
        <view class="top-item">
          <text class="item-label">
            共获得星币
          </text>
          <text class="item-text">
            {{ accountData?.balance }}枚
          </text>
        </view>
      </view>

      <view class="content-calendar">
        <view class="calendar-top">
          <text v-for="(day, i) in weekText" :key="i" class="top-item">
            {{ day }}
          </text>
        </view>
        <view class="calendar-content">
          <view v-for="(row, i) in weeks" :key="`row${i}`" class="calendar-row">
            <view v-for="(day, j) in row" :key="day.num + j" class="calendar-item">
              <view v-if="day.num" class="item-content" :class="`item-content-${day.status}`">
                <text class="item-num">
                  {{ day.num }}
                </text>
                <image v-if="day.status === 0" class="item-img" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/sign_yes.png" />
                <image v-if="day.status === 2" class="item-img" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/sign_no.png" />
                <image v-if="day.status === 1" class="item-img" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/sign_success.png" />
                <text class="item-info">
                  {{ day.affect }}星币
                </text>
              </view>
            </view>
          </view>

          <view v-if="userStore.signStatus === '0'" class="cotent-btn" @click="handleClick">
            立即签到
          </view>
          <view class="content-info">
            <text class="info-date">
              {{ new Date().getMonth() + 1 }}月1日 - {{ new Date().getMonth() + 1 }}月{{ new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate() }}日
            </text>
            <view class="info-value">
              还剩
              <text class="info-value-num">
                {{ new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate() - new Date().getDate() }}
              </text>
              天
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
  <IpOverlay v-model:show="showSign" :number="signNumber" :info="signInfo" />
</template>

<script lang="ts" setup>
import IpOverlay from '@/components/ipOverlay/index.vue';
import NavigationBar from '@/components/navigation-bar/index.vue';
import { doSign, getIntegralAccount, getMonthSignRecord } from '@/api/sign/index';
import type { DoSignResult, GetIntegralAccountResult, GetMonthSignRecordResult } from '@/api/sign/type';
import { useUserStore } from '@/store';
import { getNavigationHeight } from '@/utils/auth/index';
import { formatSimpleDate } from '@/utils/common/index';

const userStore = useUserStore();

const totalNavigationHeight = ref(getNavigationHeight());

const weekText = ref<Array<string>>(['日', '一', '二', '三', '四', '五', '六']);
const year = ref<number>(new Date().getFullYear());
const month = ref<number>(new Date().getMonth()); // 0-based
// 获取当前月每周的日期
const weeks = ref<Array<{ date: string; num: number; status: number; affect: string }[]>>([]); // status: 0: 默认 1: 已签到 2: 未签到
const setWeekData = () => {
  weeks.value = [];
  const currentDate = new Date(year.value, month.value, 1);
  const currentWeekStart = new Date(currentDate);

  // 找到第一个周日之前的日期
  while (currentWeekStart.getDay() !== 0) {
    currentWeekStart.setDate(currentWeekStart.getDate() - 1);
  }

  // 遍历整个月份，按周划分
  while (
    (currentWeekStart.getMonth() <= month.value && currentWeekStart.getFullYear() === year.value)
    || (currentWeekStart.getFullYear() === year.value - 1 && currentWeekStart.getMonth() === 11)
  ) {
    const week: ({ date: string; num: number; status: number; affect: string })[] = [];
    for (let i = 0; i < 7; i++) {
      const day = new Date(currentWeekStart);
      day.setDate(day.getDate() + i);
      if (day.getMonth() === month.value && day.getFullYear() === year.value) {
        week.push({
          date: formatSimpleDate(day),
          num: day.getDate(),
          status: day.getDate() < new Date().getDate() ? 2 : 0,
          affect: day.getDate() < new Date().getDate() ? '0' : '10',
        });
      }
      else {
        week.push({
          date: formatSimpleDate(day),
          num: 0,
          status: day.getDate() < new Date().getDate() ? 2 : 0,
          affect: '0',
        });
      }
    }
    weeks.value.push(week);
    currentWeekStart.setDate(currentWeekStart.getDate() + 7);
  }
};

const accountData = ref<GetIntegralAccountResult>();
const getTotal = () => {
  getIntegralAccount().then((res: GetIntegralAccountResult) => {
    accountData.value = res;
  });
};

const getList = () => {
  getMonthSignRecord().then((res: Array<GetMonthSignRecordResult>) => {
    for (let r = 0; r < weeks.value.length; r++) {
      const rowItem = weeks.value[r];
      for (let i = 0; i < rowItem.length; i++) {
        const item = rowItem[i];
        const findItem = res.find((data: GetMonthSignRecordResult) => data.day === item.date);
        if (findItem) {
          item.status = findItem.type === 1 ? 1 : 0;
          item.affect = findItem.affect;
        }
      }
    }
  });
};

const showSign = ref(false);
const signNumber = ref<string>('');
const signInfo = ref<string>('');
let loading: boolean;
// 立即签到
const handleClick = () => {
  if (loading)
    return;
  loading = true;
  doSign({ type: '1' }).then((res: DoSignResult) => {
    signNumber.value = res.lastSignIntegral ? `${res.todayIntegral - res.lastSignIntegral}+${res.lastSignIntegral}` : res.todayIntegral.toString();
    signInfo.value = res.lastDays > 0 ? `已连续签到${res.lastDays}天，明天签到可额外获得5星币` : '';
    showSign.value = true;
    userStore.setSignStatus('1');
    setWeekData();
    getTotal();
    getList();
  }).finally(() => {
    loading = false;
  });
};

setWeekData();
getTotal();
getList();

// 分享
uni.showShareMenu({
  withShareTicket: true,
  menus: ['shareAppMessage', 'shareTimeline'],
});
onShareAppMessage(() => {
  return {
    title: userStore.share_txt,
    imageUrl: userStore.share_pic_url,
  };
});
</script>

<style lang="scss" scoped>
.sign-in {
  position: relative;
  height: 100%;
  background: #B7EC98;
  display: flex;
  flex-direction: column;

  .sign-title {
    position: relative;
    padding: 20rpx 40rpx 40rpx 40rpx;
    display: flex;
    flex-direction: column;

    .title-text {
      font-size: 56rpx;
      color: #547A36;
      line-height: 84rpx;
    }

    .title-info {
      padding-top: 8rpx;
      font-size: 28rpx;
      color: #547A36;
      line-height: 42rpx;
    }

    .sign-img {
      position: absolute;
      right: 32rpx;
      bottom: -64rpx;
      width: 220rpx;
      height: 218rpx;
    }
  }

  .sign-content {
    position: relative;
    flex: 1;
    overflow: hidden;
    padding: 64rpx 32rpx 0;
    background: #fff;
    border-radius: 40rpx 40rpx 0 0;
    display: flex;
    flex-direction: column;

    .content-top {
      display: flex;
      padding-bottom: 32rpx;
      border-bottom: 2rpx dashed #EDEDED;

      .top-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        padding-right: 40rpx;

        .item-label {
          font-size: 28rpx;
          color: #313131;
          line-height: 42rpx;
        }

        .item-text {
          padding-top: 8rpx;
          font-size: 32rpx;
          color: #FF7E33;
          line-height: 48rpx;
        }
      }
    }

    .content-calendar {
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      padding-top: 32rpx;

      .calendar-top {
        display: flex;
        justify-content: space-between;

        .top-item {
          width: 88rpx;
          text-align: center;
          font-size: 24rpx;
          color: #313131;
          line-height: 40rpx;
        }
      }

      .calendar-content {
        flex: 1;
        overflow: auto;

        .calendar-row {
          display: flex;
          justify-content: space-between;
          padding-top: 12rpx;

          .calendar-item {
            width: 88rpx;

            .item-content {
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              padding: 8rpx;
              background: #FEF9ED;
              border-radius: 16rpx;
              color: #FF7E33;

              .item-num {
                font-size: 20rpx;
                line-height: 30rpx;
              }

              .item-img {
                margin-top: 4rpx;
                margin-bottom: 12rpx;
                width: 40rpx;
                height: 40rpx;
              }

              .item-info {
                font-size: 16rpx;
                line-height: 24rpx;
              }
            }

            .item-content-1 {
              background: #E0FFF8;
              color: #0BC296;
            }

            .item-content-2 {
              background: #EFEFEF;
              color: #87837B;
            }
          }
        }

        .cotent-btn {
          margin-top: 48rpx;
          width: 100%;
          background: linear-gradient( 90deg, #FFA029 0%, #FFCD29 100%);
          border-radius: 46rpx;

          font-weight: bold;
          font-size: 32rpx;
          text-align: center;
          line-height: 92rpx;
          color: #FFFFFF;
        }

        .content-info {
          margin-top: 48rpx;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-bottom: 60rpx;

          .info-date {
            flex: 1;
            font-size: 24rpx;
            color: #87837B;
            line-height: 36rpx;
          }

          .info-value {
            font-size: 24rpx;
            color: #87837B;
            line-height: 36rpx;

            .info-value-num {
              display: inline-block;
              padding: 0 8rpx;
              color: #FB7C00;
            }
          }
        }
      }
    }
  }
}
</style>
